<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div class="profile-header">
        <div class="profile-header-top">
          <el-button 
            type="primary" 
            plain 
            @click="$router.push('/')"
            class="back-home-btn"
          >
            返回首页
          </el-button>
        </div>
        <el-avatar :size="100" :src="userInfo.profilePicture" />
        <h2>{{ userInfo.nickName }}</h2>
        
        <el-row :gutter="20" class="stats-row">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ userInfo.postCount || 0 }}</div>
              <div class="stat-label">帖子量</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ userInfo.likeCount || 0 }}</div>
              <div class="stat-label">点赞量</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ userInfo.visitCount || 0 }}</div>
              <div class="stat-label">访问量</div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <el-tabs v-model="activeTab" class="profile-tabs">
        <el-tab-pane v-if="isCurrentUser" label="个人信息" name="info">
          <el-form :model="userInfo" label-width="80px">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :http-request="uploadAvatar"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="userInfo.profilePicture" :src="userInfo.profilePicture" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="昵称">
              <el-input v-model="userInfo.nickName" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateProfile">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane v-if="isCurrentUser" label="修改密码" name="password">
          <el-form 
            :model="passwordForm" 
            label-width="80px" 
            :rules="passwordRules" 
            ref="passwordFormRef"
          >
            <el-form-item label="旧密码" prop="oldPassword">
              <el-input 
                v-model="passwordForm.oldPassword" 
                type="password" 
                show-password
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="passwordForm.newPassword" 
                type="password" 
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="passwordForm.confirmPassword" 
                type="password" 
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="changePassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane :label="isCurrentUser ? '我的帖子' : '他的帖子'" name="posts">
          <div class="post-list">
            <div v-if="postList.length === 0" class="empty-post">
              暂无技术问题，欢迎踊跃参与互动~
            </div>
            <div class="post-item" v-for="post in postList" :key="post.postId">
              <div class="stats">
                <div class="votes">
                  <span class="count">{{ post.visitCount }}</span>
                  <span>浏览量</span>
                </div>
                <div class="answers" :class="{ answered: post.replyCount > 0 }">
                  <span class="count">{{ post.replyCount }}</span>
                  <span>回答量</span>
                </div>
                <div class="views">
                  <span class="count">{{ post.likeCount }}</span>
                  <span>点赞量</span>
                </div>
              </div>
              <div class="content" @click="goToPostDetail(post.postId)">
                <h3 class="title">
                  {{ post.postTitle }}
                </h3>
                <div class="excerpt">{{ post.postContent }}</div>
                <div class="meta">
                  <div class="boards">
                    <span class="board" v-for="board in post.boards.split('、')" :key="board">
                      {{ board }}
                    </span>
                  </div>
                  <div class="user-info">
                    <span class="time">{{ post.time }}</span>
                    <div class="actions" v-if="isCurrentUser">
                      <el-button size="small" type="primary" @click.stop="editPost(post)">修改</el-button>
                      <el-button size="small" type="danger" @click.stop="deletePost(post)">删除</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane v-if="isCurrentUser" label="我的收藏" name="favorites">
          <div class="favorite-list">
            <div v-if="favoriteList.length === 0" class="empty-post">
              暂无收藏技术问题，欢迎踊跃收藏~
            </div>
            <div class="post-item" v-for="post in favoriteList" :key="post.postId">
              <div class="stats">
                <div class="votes">
                  <span class="count">{{ post.visitCount }}</span>
                  <span>浏览量</span>
                </div>
                <div class="answers" :class="{ answered: post.replyCount > 0 }">
                  <span class="count">{{ post.replyCount }}</span>
                  <span>回答量</span>
                </div>
                <div class="views">
                  <span class="count">{{ post.likeCount }}</span>
                  <span>点赞量</span>
                </div>
              </div>
              <div class="content" @click="goToPostDetail(post.postId)">
                <h3 class="title">
                  {{ post.postTitle }}
                </h3>
                <div class="excerpt">{{ post.postContent }}</div>
                <div class="meta">
                  <div class="boards">
                    <span class="board" v-for="board in post.boards.split('、')" :key="board">
                      {{ board }}
                    </span>
                  </div>
                  <div class="user-info">
                    <span class="time">{{ post.time }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getUserInfoOtherService, 
  updateUserInfoService, 
  changePasswordService, 
  getUserPostsService, 
  uploadAvatarService, 
  getUserFavoritesService 
} from '@/apis/profile'
import { deletePostService } from '@/apis/post'

interface UserInfo {
  nickName: string
  profilePicture: string
  userId: string
  postCount: number
  likeCount: number
  visitCount: number
  isCurrent: boolean
}

interface Post {
  postId: string
  visitCount: number
  replyCount: number
  likeCount: number
  postTitle: string
  postContent: string
  time: string
  boards: string
}

const route = useRoute()
const router = useRouter()

const userInfo = ref<UserInfo>({
  nickName: '',
  profilePicture: '',
  userId: '',
  postCount: 0,
  likeCount: 0,
  visitCount: 0,
  isCurrent: false
})

const isCurrentUser = ref(false)
const activeTab = ref('info')
const passwordFormRef = ref()
const postList = ref<Post[]>([])
const favoriteList = ref<Post[]>([])
const postLoading = ref(false)

const passwordForm = ref({
  userId: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const uploadAvatar = async (file: any) => {
  const formData = new FormData()
  formData.append('file', file.file)
  formData.append('userId', userInfo.value.userId)
  try {
    const res = await uploadAvatarService(formData)
    if (res.code === 1000) {
      userInfo.value.profilePicture = res.data
      ElMessage.success('头像更新成功')
    } else {
      ElMessage.error(res.message)
    }
  } catch (error) {
    ElMessage.error('上传失败，请重试')
  }
}

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const fetchUserInfo = async () => {
  const userId = route.query.userId as string
  try {
    const res = await getUserInfoOtherService({ userId })
    if (res.code === 1000) {
      userInfo.value = res.data
      passwordForm.value.userId = res.data.userId
      isCurrentUser.value = res.data.isCurrent
    } else {
      throw new Error(res.message || '获取用户信息失败')
    }
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const updateProfile = async () => {
  try {
    const res = await updateUserInfoService({
      userId: userInfo.value.userId,
      nickName: userInfo.value.nickName,
      profilePicture: userInfo.value.profilePicture
    })
    if (res.code === 1000) {
      ElMessage.success('修改成功')
    } else {
      throw new Error(res.message || '修改失败')
    }
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    const res = await changePasswordService({
      userId: userInfo.value.userId,
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword,
      confirmPassword: passwordForm.value.confirmPassword
    })
    
    if (res.code === 1000) {
      ElMessage.success('密码修改成功')
      passwordForm.value = {
        userId: userInfo.value.userId,
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    } else {
      throw new Error(res.message || '密码修改失败')
    }
  } catch (error) {
    if (error.message !== '验证失败') {
      ElMessage.error(error.message)
    }
  }
}

const fetchUserPosts = async () => {
  postLoading.value = true
  try {
    const userId = route.query.userId as string
    const res = await getUserPostsService({ userId })
    postList.value = res || []
  } catch (error) {
    ElMessage.error('获取帖子列表失败')
  } finally {
    postLoading.value = false
  }
}

const fetchUserFavorites = async () => {
  postLoading.value = true
  try {
    const userId = route.query.userId as string
    const res = await getUserFavoritesService({ userId })
    favoriteList.value = res || []
  } catch (error) {
    ElMessage.error('获取收藏列表失败')
  } finally {
    postLoading.value = false
  }
}

const goToPostDetail = (postId: string) => {
  router.push(`/forum/detail/${postId}`)
}

const editPost = (post: Post) => {
  router.push({ name: 'Post', query: { postId: post.postId, editMode: 'true' } })
}

const deletePost = async (post: Post) => {
  try {
    await ElMessageBox.confirm('确定要删除该帖子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deletePostService(post.postId)
    if (res.code === 1000) {
      ElMessage.success('删除成功')
      fetchUserPosts()
    } else {
      throw new Error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message)
    }
  }
}

onMounted(async () => {
  await fetchUserInfo()
  if (!isCurrentUser.value) {
    activeTab.value = 'posts'
  }
  await fetchUserPosts()
})

watch(activeTab, (newVal) => {
  if (newVal === 'posts') {
    fetchUserPosts()
  } else if (newVal === 'favorites') {
    fetchUserFavorites()
  }
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.profile-header {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 0;
}

.profile-header-top {
  position: absolute;
  top: 10px;
  right: 10px;
}

.profile-header h2 {
  margin-top: 15px;
  margin-bottom: 10px;
  font-size: 24px;
}

.back-home-btn {
  margin-top: 10px;
}

.stats-row {
  margin-top: 20px;
  width: 100%;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.profile-tabs {
  margin-top: 20px;
}

.post-list,
.favorite-list {
  margin-top: 20px;
}

.post-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
}

.post-item:hover {
  background-color: #f5f7fa;
}

.stats {
  width: 120px;
  text-align: center;
  color: #909399;
}

.stats .count {
  display: block;
  font-size: 16px;
  margin-bottom: 5px;
}

.content {
  flex: 1;
  padding-left: 20px;
}

.title {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #303133;
}

.excerpt {
  color: #606266;
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.boards .board {
  display: inline-block;
  margin-right: 8px;
  padding: 0 8px;
  font-size: 12px;
  line-height: 20px;
  color: #409EFF;
  background-color: #ecf5ff;
  border-radius: 4px;
}

.time {
  color: #909399;
  font-size: 12px;
}

.empty-post {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.avatar-uploader {
  display: inline-block;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  font-size: 28px;
  color: #8c939d;
  background: #f5f7fa;
  border-radius: 50%;
}

.actions {
  margin-left: 10px;
}

.answers.answered {
  color: #67C23A;
}
</style>